package com.edfapp.costom;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author hong
 * @description 描述
 * @time 2025/11/14 18:18
 **/
public class EdfAnnotationsDecoder {
    /*----- ① 用 record 代替 POJO -----*/
    public record Event(double timeSeconds, String text) {
        @Override
        public String toString() {
            return String.format("%.3f s\t%s", timeSeconds, text);
        }
    }

    /*----- ② 解析入口 -----*/
    public static List<Event> parse(double[] raw) {
        List<Event> events = new ArrayList<>();

        // 1. double -> 无符号 byte
        byte[] bb = new byte[raw.length];
        for (int i = 0; i < raw.length; i++) {
            bb[i] = (byte) ((int) raw[i] & 0xFF);
        }

        // 2. 整块当 ASCII
        String tal = new String(bb, StandardCharsets.US_ASCII);

        // 3. 按 TAL 结束符 0x14 分块
        int p = 0, len = tal.length();
        while (p < len) {
            int end = tal.indexOf((char) 0x14, p);
            if (end == -1) break;
            if (end > p) {
                String block = tal.substring(p, end);
                // 4. 按 0x15 拆分
                String[] part = block.split("\u0015", -1);
                if (part.length >= 3) {
                    double onset = Double.parseDouble(part[0]);
                    String txt   = String.join("|", Arrays.copyOfRange(part, 2, part.length));
                    events.add(new Event(onset, txt));
                }
            }
            p = end + 1;
        }
        return events;
    }

    /*----- ③ 简单自测 -----*/
    public static void main(String[] args) {
        // 模拟字节流： "12.5\x15\x15Sleep stage 2\x14"
        double[] mock = {11056.000000,5140.000000,43.000000,12309.000000,13358.000000,12820.000000,21552.000000,5120.000000,0.000000,0.000000,
                0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,
                11057.000000,5140.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000
        };
        List<Event> list = parse(mock);
        list.forEach(System.out::println);
    }
}
